package com.ktjy.springredis;

import com.ktjy.springredis.entity.User;
import com.ktjy.springredis.service.IUserService;
import jakarta.annotation.Resource;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;


import java.util.List;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class RedisTemplateTester {
    @Resource
    private StringRedisTemplate stringRedisTemplate; // 操作字符串数据

    @Resource
    private RedisTemplate redisTemplate; // 操作其他数据类型

    @Test
    public void testString() {
     stringRedisTemplate.opsForValue().set("name", "ktjy");
//     Assert.assertEquals("ktjy", stringRedisTemplate.opsForValue().get("name"));
    }

    @Test
    public void testObj(){
        User user = new User("czkt", "123456", 1L, null);
        ValueOperations<String, User> operations = redisTemplate.opsForValue();
        operations.set("com.ktjy.springredis.entity.User", user);
        User u = operations.get("com.ktjy.springredis.entity.User");
        System.out.println("u.getUsrName():"+u.getUsrName());
    }
    //超时失效
    @Test
    public void testExpire(){
        User user = new User("czkt", "123456", 1L, null);
        ValueOperations<String, User> operations = redisTemplate.opsForValue();

        // 使用秒或毫秒作为时间单位
        operations.set("expire", user, 1, TimeUnit.SECONDS);// 设置1秒超时
        try {
            System.out.println("立即检查 - 存在: " + redisTemplate.hasKey("expire"));
            Thread.sleep(1500); // 等待1.5秒
            System.out.println("1.5秒后检查 - 存在: " + redisTemplate.hasKey("expire"));
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            System.err.println("线程被中断");
        }
    }
    //操作哈希
    @Test
    public void testHash(){
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        hashOperations.put("hash", "name", "ktjy");
        String value=(String) hashOperations.get("hash", "name");
        System.out.println("value:"+value);
    }
    //操作列表
    @Test
    public void testList(){
        ListOperations<String, String> listOperations = redisTemplate.opsForList();
        listOperations.leftPush("list", "ktjy");
//        listOperations.leftPush("list", "czkt");
        String value = listOperations.leftPop("list");
        System.out.println("value:"+value.toString());
    }
    @Resource
    private IUserService userService;
    @Test
    public void testGetUser(){
        User user = userService.getUser(2L);
        System.out.println("userName:"+user.getUsrName());
    }
}